/*
 * Created on 2005-4-13
 *
 * Copyright: Bluejay Networks Inc. 2005
 *
 * This software is the proprietary information of Bluejay Networks Inc. 
 * 
 * Use is subject to license terms.
 * 
 */
package com.ims.iaa;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
/**
 * @author ShengMengBai
 *
 * Because java.net.URL class has some bug and it is final class,
 * so I new a class to get the URL.
 * fixed next bug:
 * 1) Don't escape the blank of URL String
 * 2) if use a exist URL and a string to create a new URL may be not correct.
 */
public class URLUtil{
    public static URL getURL(String sURL) throws MalformedURLException{
        try {
            sURL = URLDecoder.decode(sURL, "UTF-8");
        } catch (Exception e) {}
        URL url = new URL(escape(sURL));
        String sSlash = url.getPath();
        //if there are root path, add it.
        if(sSlash != null){
	        if(sSlash.length() == 0){
	            url = new URL(url, "/");
	        }
        }
        return url;
    }
    public static URL getURL(URL ctx, String sURL) throws MalformedURLException{
        try {
            sURL = URLDecoder.decode(sURL, "UTF-8");
        } catch (Exception e) {}
        int iBackCount = 0;
        //calculate the slash count of path
        int iSlashCount = 0;
        String sSlash = ctx.getPath();
        int iSlashIdx = sSlash.indexOf("/");
        while(iSlashIdx != -1){
            iSlashIdx = sSlash.indexOf("/", iSlashIdx + 1);
            iSlashCount++;
        }
        //if the string start with ../, we will deal with it.
        int iBackIdx = sURL.indexOf("../");
        if(iBackIdx == 0){
            //count the step of back
	        while(iBackIdx != -1){
	            iBackIdx = sURL.indexOf("../", iBackIdx + 3);
	            iBackCount++;
	        }
	        //if the back symbol is too more, delete it.
	        if(iBackCount >= iSlashCount){
	            int iDelCount = iBackCount - iSlashCount + 1;
	            sURL = sURL.substring(3 * iDelCount);
	        }
        }else{
            //some URL maybe like this: \image1.gif, 
            //in this instance, it means the image in the root of site.
            iBackIdx = sURL.indexOf("\\");
            if(iBackIdx == 0){
                while(iBackIdx != -1){
                    sURL = sURL.substring(1);
                    iBackIdx = sURL.indexOf("\\");
                }
                //add the ../
                for(int i = 1; i < iSlashCount; i++){
                    sURL = "../" + sURL; 
                }
            }
        }
        return new URL(ctx, escape(sURL));
    }
    private static String escape(String sURL){
        return sURL.replaceAll(" ", "%20");
    }
	public static void main( String[] args ) {
		try  {
		    //URL url = getURL("http://noshow.adsina.allyes.com/main/adfclick?db=sina&bid=5807,25031,25071&cid=0,0,0&sid=25440&advid=802&camid=5376&show=ignore&url=http://vipchat.sina.com.cn/vip/new/6/vsimple.html");
		    //url = getURL(url, "http%3A%2F%2Fwww%2Ebuildings%2Ecom%2Fbanmanpro%2Fbanman%2Easp%3FTask%3DClick%26ZoneID%3D2%26CampaignID%3D228%26AdvertiserID%3D82%26BannerID%3D257%26SiteID%3D0%26RandomNumber%3D30436");
		   //System.out.println(url);
		    //url = getURL(url, "../index.html");
		    //System.out.println(url);
		    System.out.println(escapeSlash("http://www.baidu.com/"));
		    System.out.println(escapeSlash("http://www.baidu.com"));
		    
		} catch (Exception e){
		    e.printStackTrace();
		}
	}
	
	//++changsheng 2006-6-20
	public static String escapeSlash(String sUrl)
	{
		if(sUrl == null ) return null ;
		char c = sUrl.charAt(sUrl.length() -1 );
		if(c == '/')
		{
			return sUrl.substring(0,sUrl.length() -1 ) ;
		}
		return sUrl ;	
	}
	//--
	
	
	//++changsheng 2006-7-19
	public static boolean compareURL(String src1 ,String src2 )
	{
	    boolean retValue = false ;
	    try {
            if(src1.equals(src2) )
            {
                return true ;
            }
            URL $1 = new URL( src1 ) ;
            URL $2 = new URL( src2 ) ;
            if( $1.getProtocol().equals($2.getProtocol())
             && $1.getPath().equals($2.getPath())
             && $1.getHost().equals($2.getHost())  )
            {
                if($1.getQuery() == null && $2.getQuery() == null)
                {
                    return true  ;//impossible
                }
                else if($1.getQuery() == null || $2.getQuery() == null)
                {
                    return false ;
                }
                String[] $3 =  $1.getQuery().split("&") ;
                String[] $4 =  $2.getQuery().split("&") ;
                if($3.length == $4.length)
                {
                    boolean whole_flag = true  ;
                    for(int i = 0 ; i < $3.length ; i ++ )
                    {
                        boolean part_flag = false  ;
                        for(int j = 0 ; j < $4.length ; j ++ )
                        {
                            if($3[i].split("=")[0].equals($4[j].split("=")[0]))
                            {
                                part_flag = true ;
                                break ;
                            }
                        }
                        if( part_flag == false )
                        {
                            whole_flag = false ;
                        }
                        if(whole_flag == false )
                        {
                            return false ;
                        }
                    }
                    retValue = whole_flag ;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false ;
        }
        return retValue;
	}
	//--
}
